package com.dlc.apk.service.staff.impl

import com.dlc.apk.api.ApiConstants
import com.dlc.apk.api.ApiManager
import com.dlc.apk.api.BaseResponseModel
import com.dlc.apk.api.entity.StaffLoginResponseData
import com.dlc.apk.service.staff.IStaffService
import com.dlc.apk.ui.model.LoginFrom
import com.dlc.apk.utils.CacheHelper
import com.dlc.apk.utils.GsonUtil
import com.dlc.apk.utils.LogPlus
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

class StaffService : IStaffService {
    override fun login(form: LoginFrom) {
        if (form.account.get()!!.isEmpty()) {
            form.onProcessListener.onFailure(java.lang.RuntimeException("请输入账号"), "请输入账号")
            return
        }
        if (form.password.get()!!.isEmpty()) {
            form.onProcessListener.onFailure(java.lang.RuntimeException("请输入密码"), "请输入密码")
            return
        }
        form.onProcessListener.onStart()
        ApiManager.instance.apiService
            .login(phone = form.account.get(), password = form.password.get())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<BaseResponseModel<StaffLoginResponseData>> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(objectBaseResponseModel: BaseResponseModel<StaffLoginResponseData>) {
                    if (objectBaseResponseModel.code != ApiConstants.CODE_SUCCESS) {
                        form.onProcessListener.onFailure(RuntimeException(objectBaseResponseModel.msg), objectBaseResponseModel.msg)
                        form.onProcessListener.onComplete()
                        return
                    }
                    LogPlus.e("###data -> " + GsonUtil.instance.parseObjToJsonStr(objectBaseResponseModel))
                    CacheHelper.saveStaffToken(objectBaseResponseModel.data?.token)
                    form.onProcessListener.onSuccess()
                    form.onProcessListener.onComplete()
                }

                override fun onError(e: Throwable) {
                    LogPlus.e("###请求出错->" + LogPlus.getStackTraceInfo(e))
                    form.onProcessListener.onFailure(e, e.message)
                    form.onProcessListener.onComplete()
                }

                override fun onComplete() {}
            })
    }
}